package com.tool.ui;

import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Window;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 * 弹窗基类
 * 
 * @author Evan.Hu
 * 
 */
public class DialogUIHelper extends JDialog {
	private static final long serialVersionUID = 3546867108679281344L;
	private CoreUI ui = null;
	private Window owner = null;

	public DialogUIHelper(JFrame owner, CoreUI ui, boolean isModal) {
		super(owner, isModal);
		this.owner = owner;
		this.ui = ui;
	}

	public DialogUIHelper(JDialog owner, CoreUI ui, boolean isModal) {
		super(owner, isModal);
		this.owner = owner;
		this.ui = ui;
	}

	public void show() {

		ui.setWindow(this);
		setIconImage(ui.getIconImage());
		this.setTitle(ui.getTitle());
		this.setPreferredSize(ui.getPreferredSize());
		this.getRootPane().setMenuBar(ui.getMenuBar());
		this.getContentPane().add(ui);
		setLocationRelativeTo(owner);

		try {
			ui.onLoad();
		} catch (Exception e) {
			JOptionPane.showMessageDialog(owner, e.getMessage(), "", JOptionPane.ERROR_MESSAGE);
			return;
		}
		this.setResizable(ui.isResizable());

		this.pack();

		Rectangle screenRect = getGraphicsConfiguration().getBounds();
		Insets screenInsets = Toolkit.getDefaultToolkit().getScreenInsets(getGraphicsConfiguration());

		// Make sure we don't place the demo off the screen.
		int centerWidth = screenRect.width < getSize().width ? screenRect.x : screenRect.x + screenRect.width / 2 - getSize().width / 2;
		int centerHeight = screenRect.height < getSize().height ? screenRect.y : screenRect.y + screenRect.height / 2 - getSize().height / 2;

		centerHeight = centerHeight < screenInsets.top ? screenInsets.top : centerHeight;

		setLocation(centerWidth, centerHeight);
		super.show();
	}
}
